package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.CustomExcepton;
import com.itheima.dto.SetmealDto;
import com.itheima.entity.Setmeal;
import com.itheima.entity.SetmealDish;
import com.itheima.mapper.SetmealMapper;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceimpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    //新增套餐，同时需要保存套餐和菜品的关联关系
    @Override
    @Transactional
    public void saveDish(SetmealDto setmealDto) {
        //保存套餐的基本信息，操作setmeal，执行insert操作
        this.save(setmealDto);
        //创建有关联关系的集合对象
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //因为SetmealDish中的setmealid没有值，
        // 所以需要将集合遍历然后给setmealid赋上值
        setmealDishes = setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        //保存套餐和菜品的关联信息，操作setmeal_dish和执行insert操作
        setmealDishService.saveBatch(setmealDishes);
    }
    //        删除套餐
    @Transactional
    public void deletes(List<Long> ids) {
//查询套餐是否有关联数据，确定是否可以删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //查看当前状态
        queryWrapper.eq(Setmeal::getStatus,1);
        //获取数据id
        queryWrapper.in(Setmeal::getId,ids);
//上面两条大概的sql语句为select count(*) from where id  in (1,2,3) and status=1
        //调用mp中的count方法
        int count = this.count(queryWrapper);
        //判断count是否大于零，判断是否正在售卖
        if (count>0){
            throw new CustomExcepton("套餐正在售卖，删除失败");
        }
        //没有售卖，进行删除，先删除从表数据（菜品）
        LambdaQueryWrapper<SetmealDish> queryWrapper1 = new LambdaQueryWrapper<>();
        //获取关联套餐的getSetmealId
        queryWrapper1.in(SetmealDish::getSetmealId,ids);
        //删除菜品表数据
       setmealDishService.remove(queryWrapper1);
        //删除套餐表中的数据
        this.removeByIds(ids);
    }
}
